<?php

namespace App\Exceptions;

use App\Library\UpTools;
use Exception;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Illuminate\Http\JsonResponse;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

class Handler extends ExceptionHandler
{
    /**
     * A list of the exception types that should not be reported.
     *
     * @var array
     */
    protected $dontReport = [
        \Illuminate\Auth\AuthenticationException::class,
        \Illuminate\Auth\Access\AuthorizationException::class,
        \Symfony\Component\HttpKernel\Exception\HttpException::class,
        \Illuminate\Database\Eloquent\ModelNotFoundException::class,
        \Illuminate\Session\TokenMismatchException::class,
        \Illuminate\Validation\ValidationException::class,
    ];

    /**
     * Render an exception into an HTTP response.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Exception  $exception
     * @return \Illuminate\Http\Response
     */
    public function render($request, Exception $exception)
    {
        $e = $this->prepareException($exception);

        return $this->prepareJsonResponse($request, $e);
    }

    protected function prepareJsonResponse($request, Exception $e)
    {
        $status = 200;

        $headers = $this->isHttpException($e) ? $e->getHeaders() : [];

        if ($e instanceof NotFoundHttpException) {
            return redirect("/");
        }else {
            return new JsonResponse(
                $this->convertExceptionToArray($e), $status, $headers,
                JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES
            );
        }
    }

    /**
     * Convert the given exception to an array.
     *
     * @param  \Exception  $e
     * @return array
     */
    protected function convertExceptionToArray(Exception $e)
    {
        if(strpos($e->getTraceAsString(), "/vendor/laravel/framework/src/Illuminate/Routing/Router.php") === false) {
            UpTools::writeLog(var_export($e->getLine() . $e->getMessage() . $e->getTraceAsString(), true), "exception.txt");
        }
        return [
            "code" => 444,
            'msg' => $e->getMessage() ?: get_class($e),
            'file' => $e->getFile(),
            'line' => $e->getLine()
        ];
    }

    /**
     * Convert an authentication exception into an unauthenticated response.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Illuminate\Auth\AuthenticationException  $exception
     * @return \Illuminate\Http\Response
     */
    protected function unauthenticated($request, AuthenticationException $exception)
    {
        if ($request->expectsJson()) {
            return response()->json(['error' => 'Unauthenticated.'], 401);
        }

        return redirect()->guest('login');
    }
}
